var token = require('../public/javascripts/utils');
var express = require('express');
var router = express.Router();
var db = require('../public/javascripts/db');
var crypto = require('crypto');
const jwt = require('jsonwebtoken');
const fs = require('fs');
const path = require('path');

// 生成token
// function generateToken(data) {
//     let created = Math.floor(Date.now() / 1000);
//     // console.log(created + 3600 * 24 * 7)
//     let cert = fs.readFileSync(path.join(__dirname, '../public/rsa_private_key.pem'));
//     let token = jwt.sign({
//         data,
//         exp: created + 3600 * 24 * 7
//         // exp: created + 10
//     }, cert, {algorithm: 'RS256'})
//     return token;
// }

router.post('/', (req, res, next) => {
    // console.log(req);
    var sql = 'SELECT * FROM user WHERE username = ?';
    var sql2 = 'SELECT * FROM user WHERE mail = ?';
    db.query(sql, req.body.username, (err, result) => {
        if (err) {
            throw err;
            return;
        } else {
            var md5 = crypto.createHash('md5');
            var newPas = md5.update(req.body.password).digest('hex');
            if (result.length == 0) {
                db.query(sql2, req.body.username, (err, info) => {
                    if (err) {
                        throw err;
                        return;
                    } else {
                        if (info.length == 0) {
                            res.send({status: 0});
                        } else if (info[0].password != newPas) {
                            res.send({status: 1});
                        } else {
                            var data = {
                                status: 2,
                                token: token.generateToken(req.body.username)
                            }
                            res.send(data);
                        }
                    }
                })
            } else if (result[0].password != newPas) {
                res.send({status: 1});
            } else {
                var data = {
                    status: 2,
                    token: token.generateToken(req.body.username)
                }
                res.send(data);
            }
        }
    })
})

module.exports = router;